package com.jf3q.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduOrder;
import com.jf3q.common.mapper.EduCourseMapper;
import com.jf3q.common.mapper.EduOrderMapper;
import com.jf3q.common.service.EduMemberService;
import com.jf3q.common.utils.OrderCodeUtils;
import com.jf3q.common.vo.CourseWebVo;
import com.jf3q.front.service.EduOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 *
 */
@Service
public class EduOrderServiceImpl extends ServiceImpl<EduOrderMapper, EduOrder>
    implements EduOrderService {


    @Autowired
    EduCourseMapper eduCourseMapper;

    @Autowired
    EduMemberService eduMemberService;

    @Autowired
    EduOrderMapper eduOrderMapper;


    OrderCodeUtils orderCodeUtils;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public String createOrders(String courseId, String memberId) {
        //根据课程ID和会员ID来查询是否存在订单课程
        EduOrder eduOrder = hasOrderCourse(courseId, memberId);
        if(eduOrder!=null && eduOrder.getStatus()==0 ){
            //已经下单但未支付，这种情况直接去支付（不要再生产订单了）
            return eduOrder.getOrderNo();
        }
        if(eduOrder!=null && eduOrder.getStatus()==1 ){
            throw new RuntimeException("您已经购买过该课程，请勿重复购买");
        }
        if(eduOrder!=null && eduOrder.getStatus()==-1 ){
            throw new RuntimeException("该订单已超时，请重新下单");
        }

         //获取用户id获取用户信息
        EduMember eduMember = eduMemberService.getById(memberId);
        //根据课程id获取课程信息
        CourseWebVo courseWebVo = eduCourseMapper.selectInfoWebById(courseId);

        //给order添加数据
        EduOrder order=new EduOrder();
        order.setOrderNo(orderCodeUtils.createOrderCode(new Date()));//随机订单号
        order.setCourseId(courseId);
        order.setCourseTitle(courseWebVo.getTitle());
        order.setCourseCover(courseWebVo.getCover());
        order.setTeacherName(courseWebVo.getTeacherName());
        order.setTotalFee(courseWebVo.getPrice());
        order.setTeacherId(courseWebVo.getTeacherId());
        order.setMemberId(memberId);
        order.setMobile(eduMember.getMobile());
        order.setNickname(eduMember.getNickname());


        if(courseWebVo.getPrice()== BigDecimal.valueOf(0)){
            order.setStatus(Byte.valueOf("1"));  //订单状态（0：未支付 1：已支付）
            order.setPayType(Byte.valueOf("0"));//支付类型（0：免费课程，1：微信 2：支付宝）

            //修改课程的购买数
            Long buyCount = redisTemplate.opsForHash().increment("course_" + order.getCourseId(), "buyCount", 1);
            //修改老师的排行
            Double teacherBuyCount = redisTemplate.opsForZSet().score("teacherBuyCount", order.getTeacherId());
            redisTemplate.opsForZSet().add("teacherBuyCount",order.getTeacherId(),teacherBuyCount==null?0+buyCount:teacherBuyCount+buyCount);
        }else{
            order.setStatus(Byte.valueOf("0"));
            //暂时只接了支付宝支付，所以这里设置2
            order.setPayType(Byte.valueOf("2"));//支付类型（0：免费课程，1：微信 2：支付宝）
        }
        baseMapper.insert(order);
        //最后返回订单号
        return order.getOrderNo();
    }

    @Override
    public EduOrder selectByOrderNo(String orderNo) {
        return eduOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public EduOrder hasOrderCourse(String courseId, String memberId) {
        LambdaQueryWrapper<EduOrder> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(EduOrder::getCourseId, courseId);
        queryWrapper.eq(EduOrder::getMemberId, memberId);
        return this.getOne(queryWrapper);
    }
}




